package com.example.erp;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;

/**
 * sse 模式配置，要先启动 mcp-server-webmvc 应用服务。
 */
@Configuration
public class ClientConfig {

	// 远程mcp-server服务地址
	private static final String MCP_SERVER_BASE_URI = "http://localhost:8081";// /mcp-server
	private static final String SSE_ENDPOINT = "/sse"; // 默认/sse，可以不指定，服务器通过 /sse 发送消息给客户端

	@Bean(destroyMethod = "close")
	McpSyncClient mcpClient() {
		var transport = HttpClientSseClientTransport.builder(MCP_SERVER_BASE_URI).sseEndpoint(SSE_ENDPOINT).build();
		var mcpClient = McpClient.sync(transport).build();
		mcpClient.initialize();

		System.err.println("MCP(sse) McpSyncClient Initialized Ok.");

		return mcpClient;
	}

	@Bean
	ChatClient chatClient(ChatClient.Builder chatClientBuilder, McpSyncClient mcpClient) {
		System.err.println("MCP(sse) ChatClient Build Ok.");

		return chatClientBuilder.defaultToolCallbacks(new SyncMcpToolCallbackProvider(mcpClient)).build();
	}
}
